<template>
  <div style="margin: 10px;height: 100vh;"   v-loading="spinning">
    <el-row>
      <el-col :span="3">


        <el-row>
          <el-col :span="19" :push="2">
            <el-text tag="b">组织机构</el-text>
          </el-col>
          <el-col :span="1" :push="2">
            <el-icon :class="{'is-loading':treeSpin}" @click="getTree">
              <RefreshRight/>
            </el-icon>
          </el-col>
        </el-row>


        <el-tree
            v-loading="treeSpin"
            ref="treeRef"
            style="max-width: 600px"
            :data="treeData"
            node-key="id"
            accordion
            :props="replaceFields"
            :default-expand-all="!treeSpin"
            :highlight-current="true"
            @node-click="handleNodeClick"
            height="1vh"
            class="filter-tree"
        />
      </el-col>
      <el-col :span="21">
        <JzTable v-model:jzTableData="jzTableData"
                 v-model:queryFormInlineSubmit="queryFormInlineSubmit"
                 v-model:handleSelectionChangeData="handleSelectionChangeData"
                 @refreshClick="refreshClick"
        >
          <!--    查询表单-->
          <template v-slot:showQuery>

            <el-form ref="formRef" :inline="true"
                     :model="queryFormInline" class="demo-form-inline"
                     style="padding-left: 20px;padding-right: 20px;padding-top: 10px;">

              <el-form-item label="用户名" prop="userName">
                <el-input v-model="queryFormInline.userName" placeholder="请输入用户名" clearable/>
              </el-form-item>
              <el-form-item label="昵称" prop="nickName">
                <el-input v-model="queryFormInline.nickName" placeholder="昵称" clearable/>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="queryFormInline.phone" placeholder="手机号" clearable/>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="queryFormInline.email" placeholder="邮箱" clearable/>
              </el-form-item>
              <el-form-item label="状态" prop="isEnabled">
                <el-select
                    v-model="queryFormInline.isEnabled"
                    placeholder="请选择"
                    clearable
                    style="width: 100px"
                >
                  <el-option label="启用" value="NORMAL"/>
                  <el-option label="停用" value="STOP"/>
                </el-select>
              </el-form-item>


              <el-form-item>
                <el-button type="primary" @click="submitForm">搜索</el-button>
                <el-button @click="resetForm(formRef)">重置</el-button>
              </el-form-item>
            </el-form>

          </template>


          <!--    按钮组-->
          <template v-slot:buttonGroup>
            <el-button type="primary" @click="userSaveOrUpdateShow('')" :icon="Plus"   plain>
              新增
            </el-button>
            <el-button type="success" @click="userSaveOrUpdateShow(handleSelectionChangeData[0].id)" :icon="Edit" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1||(handleSelectionChangeData.length==1&&handleSelectionChangeData[0].userName=='admin')"  plain>
              修改
            </el-button>

            <el-button type="warning" @click="dialogVisible=true;sysMsg='确定要重置【'+handleSelectionChangeData[0].userName+'】用户密码';sysOperateType='resettingPwd';sysOperateId=handleSelectionChangeData[0].id;" :icon="View" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1||(handleSelectionChangeData.length==1&&handleSelectionChangeData[0].userName=='admin')" plain>
              重置密码
            </el-button>
            <el-button type="danger" @click="dialogVisible=true;sysMsg='确定要删除【'+handleSelectionChangeData[0].userName+'】用户信息';sysOperateType='deleteConfirm';sysOperateId=handleSelectionChangeData[0].id;" :icon="Delete" :disabled="handleSelectionChangeData==null||handleSelectionChangeData.length!=1||(handleSelectionChangeData.length==1&&handleSelectionChangeData[0].userName=='admin')" plain>
              删除
            </el-button>
          </template>

          <template v-slot:tableColumn>
            <el-table-column type="selection"  width="55" />
            <el-table-column type="index" :index="1" :fixed="'left'" label="序号"/>
            <template v-for="item in jzTableData.jzTable.zjColumnList">
              <template v-if="item.show">
                <el-table-column :label="item.label" v-if="item.prop=='isEnabledTagEnumBean'" :align="item.align" >
                  <template #default="scope">
                    <el-tag :type="scope.row.isEnabledTagEnumBean.style.type" round>{{
                        scope.row.isEnabledTagEnumBean.msg
                      }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column :label="item.label" v-else-if="item.prop=='onLine'"  width="65px" :align="item.align">
                  <template #default="scope">

                    <el-tooltip
                        class="box-item"
                        effect="dark"
                        :content="scope.row.onLine=='YES'?'在线':'离线'"
                        placement="bottom"
                    >
                      <el-icon v-if="scope.row.onLine=='YES'" color="#67C23A"><StarFilled /></el-icon>
                      <el-icon v-if="scope.row.onLine!='YES'" color="#606266" ><Star /></el-icon>
                    </el-tooltip>

                  </template>
                </el-table-column>

                <el-table-column :prop="item.prop" :label="item.label" :sortable="item.sortable?'custom':false" :align="item.align" :show-overflow-tooltip="true" v-else />

              </template>
            </template>

            <el-table-column fixed="right" label="操作" min-width="150">


              <template #default="scope">

                <el-button
                    size="small"
                    v-if="scope.row.userName!='admin'"
                    link type="success"
                    @click=" userSaveOrUpdateShow(scope.row.id)"
                    style="margin-right: 2px;margin-left:0px"
                    :icon="Edit"
                >
                  修改
                </el-button>



                <el-button   v-if="scope.row.userName!='admin'" link type="warning" size="small" @click="dialogVisible=true;sysMsg='确定要重置【'+scope.row.userName+'】用户密码';sysOperateType='resettingPwd';sysOperateId=scope.row.id;" :icon="View"  plain>
                  重置密码
                </el-button>
                <el-button   v-if="scope.row.userName!='admin'"  link type="danger" size="small" @click="dialogVisible=true;sysMsg='确定要删除【'+scope.row.userName+'】用户信息';sysOperateType='deleteConfirm';sysOperateId=scope.row.id;" :icon="Delete"  plain>
                  删除
                </el-button>
              </template>

            </el-table-column>
          </template>

        </JzTable>

      </el-col>
    </el-row>


  <el-dialog v-model="saveOrUpdateOpen" :title="saveUpdateTitle" width="800" style="z-index: 999">
    <el-form :model="userSaveOrUpdateParam" label-width="auto" style="max-width: 800px"
             ref="userSaveOrUpdateRef"
             :rules="userSaveOrUpdateRules"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="userSaveOrUpdateParam.userName" clearable :disabled="updateUserId!=''"/>
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="userSaveOrUpdateParam.nickName" clearable/>
      </el-form-item>


      <el-form-item label="密码" prop="password" v-if="updateUserId==''">
        <el-input v-model="userSaveOrUpdateParam.password" clearable show-password/>
      </el-form-item>

      <el-form-item label="所属部门" prop="departmentId">
        <el-tree-select
            v-model="userSaveOrUpdateParam.departmentId"
            :data="treeData"
            check-strictly
            :render-after-expand="false"
            node-key="id"
            style="width: 100%;background-color: #ccccff"
            :props="replaceFields"

        />


      </el-form-item>


      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userSaveOrUpdateParam.phone" clearable/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userSaveOrUpdateParam.email" clearable/>
      </el-form-item>
      <el-form-item label="是否启用">

        <el-radio-group v-model="userSaveOrUpdateParam.isEnabled">
          <el-radio value="NORMAL">启用</el-radio>
          <el-radio value="STOP">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="有效期" prop="expiredDate">

        <el-date-picker clearable
                        v-model="userSaveOrUpdateParam.expiredDate"
                        type="datetime"
                        placeholder="选择有效期"
                        style="width: 100%"
                        value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="所属角色" prop="roleIds">

        <el-select
            v-model="userSaveOrUpdateParam.roleIds"
            multiple
            placeholder="Select"
        >
          <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveSubmit(userSaveOrUpdateRef)" v-if="updateUserId==''" :loading="spinning">添加</el-button>
        <el-button type="primary" @click="updateSubmit(userSaveOrUpdateRef)" v-if="updateUserId!=''" :loading="spinning">修改</el-button>
        <el-button @click="saveOrUpdateOpen = false">取消</el-button>
      </div>
    </template>

  </el-dialog>



  <el-dialog
      v-model="dialogVisible"
      title="系统提示"
      width="500"
      align-center
  >
    <span>{{sysMsg}}</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sysOperate()" :loading="spinning">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>
<script setup lang="ts">
import {onMounted, ref, toRaw, reactive, watch} from 'vue'
import {type UserSaveOrUpdateParam, userSaveOrUpdateParam, userFromInfo} from "./userInfo";
import request from "@/api/request";
import {ElMessage, type FormInstance, type FormRules, ElTree} from "element-plus";
import {Delete, Edit, Plus, TurnOff, View} from "@element-plus/icons-vue";
import {jzTableData} from "@/components/jiaoZi/table/JzTable";
import JzTable from "@/components/jiaoZi/table/JzTable.vue";

/**
 * 左侧树开始
 *
 */
let icon = ref("WechatFilled");
const filterText = ref('')
//左侧树数据
let treeData = ref([]);
let treeSpin = ref<boolean>(false);


let handleSelectionChangeData=ref();
let roleList = ref([]);


let dialogVisible = ref<boolean>(false);
let sysMsg = ref("");
let sysOperateType=ref("");
let sysOperateId=ref("");


function sysOperate(){
  spinning.value = true;
  if(sysOperateType.value=="deleteConfirm"){
    deleteConfirm(sysOperateId.value)
  }else if(sysOperateType.value=="resettingPwd"){
    resettingPwd(sysOperateId.value)
  }


}



//左侧树数据对应的结构
const replaceFields = {
  children: 'childDepartmentList',
  label: 'departmentName',
  id: 'id',
};

/**
 * 左侧树点击方法
 * @param selectedKeys 获取到树选中的key
 */
const handleNodeClick = (data: Tree) => {
  queryFormInline.value.departmentId = data.id;
  submitForm();
}

function getTree() {
  treeSpin.value = true;
  request.get('/sysDepartment/departmentTree', {
    params: {
      'departmentTreePowerEnum': 'THIS_CHILD_DEPARTMENT',
      'departmentState': 'NORMAL'
    }
  }).then((res: any) => {
    treeSpin.value = false;
    if (res.code == '10000') {
      treeData.value = res.data;
    } else {
      ElMessage.error(res.errorMessage)
    }
  }).catch((error) => {
    treeSpin.value = false;
    ElMessage.error(error)
  })
}

/**
 * 左侧树结束
 */




/**
 * 重置密码
 */

function resettingPwd(userId:string){
  request.put('/sysUser/resettingPwd/' + userId).then((res: any) => {
    spinning.value = false;
    dialogVisible.value = false
    if (res.code == '10000') {
      ElMessage.success(res.message);
    } else {
      ElMessage.error(res.errorMessage);
      saveOrUpdateOpen.value = false;
    }
  }).catch((error) => {
    spinning.value = false;
    saveOrUpdateOpen.value = false;
  })
}


/**
 * 添加修改开始
 */


//修改的用户id
let updateUserId = ref<string>("");
//加载弹窗
let spinning = ref<boolean>(false);
//添加修改是否可见弹窗
let saveOrUpdateOpen = ref<boolean>(false)
//弹窗标题
let saveUpdateTitle = ref<string>("添加用户");

const userSaveOrUpdateRef = ref<FormInstance>()


//添加修改验证
const userSaveOrUpdateRules = reactive<FormRules<UserSaveOrUpdateParam>>({
  userName: [
    {required: true, message: '请填写用户名', trigger: 'blur'}
  ],
  nickName: [
    {required: true, message: '请填写昵称', trigger: 'blur'}
  ],
  expiredDate: [
    {required: true, message: '请选择有效期', trigger: 'blur'}
  ],
  departmentId: [
    {required: true, message: '请选择部门', trigger: 'blur'}
  ],

  password: [
    {required: true, message: '请选择密码', trigger: 'blur'}
  ],

});

//打开修改窗体
function userSaveOrUpdateShow(id: string) {
  if (id == null || id == '') {
    userFromInfo(null)
    updateUserId.value = "";
    saveUpdateTitle = ref("添加用户信息");
    saveOrUpdateOpen.value = true;

  } else {
    spinning.value = true;
    saveOrUpdateOpen.value = true;
    saveUpdateTitle.value = "修改用户信息";

    request.get('/sysUser/' + id).then((res: any) => {
      spinning.value = false;
      if (res.code == '10000') {
        updateUserId.value = id;
        userFromInfo(res.data);
      } else {
        ElMessage.error(res.errorMessage);
        saveOrUpdateOpen.value = false;
      }
    }).catch((error) => {
      spinning.value = false;
      saveOrUpdateOpen.value = false;
    })
  }
}

// 添加用户信息
const saveSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      spinning.value = true;
      request.post('/sysUser/', userSaveOrUpdateParam).then((res: any) => {
        spinning.value = false;

        if (res.code == '10000') {
          saveOrUpdateOpen.value = false;
          ElMessage.success("添加成功");
          getPage();

        }
      }).catch((error) => {
        ElMessage.error(error)
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}

//更新用户信息
const updateSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      spinning.value = true;
      request.put('/sysUser/' + updateUserId.value, userSaveOrUpdateParam).then((res: any) => {
        spinning.value = false;
        if (res.code == '10000') {
          saveOrUpdateOpen.value = false;
          ElMessage.success("修改成功");
          getPage();
        } else {
          ElMessage.error(res.errorMessage);
        }
      }).catch((error) => {
        ElMessage.error(error)
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}


/**
 * 添加修改结束
 * --------------------------------------------------------------------------
 */










const formRef = ref<FormInstance>()

//查询条件
let queryFormInline = ref({
  userName: '',
  nickName: '',
  phone: '',
  email: '',
  isEnabled: '',
  departmentId: ''
})
//查询条件点击提交的时候绑定
let queryFormInlineSubmit: any = toRaw({
  userName: '',
  nickName: '',
  phone: '',
  email: '',
  isEnabled: '',
  departmentId: ''
})


//查询条件提交
const submitForm = () => {
  jzTableData.value.jzPageData.current = 1;
  queryFormInlineSubmit = JSON.parse(JSON.stringify(queryFormInline.value));
  getPage();
}

//重置查询条件
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


//删除用户信息
const deleteConfirm = (id: any) => {

  request.delete('/sysUser/' + id).then((res: any) => {
    spinning.value = false;
    dialogVisible.value = false
    // queryFormInlineSubmit.value=null;
    if (res.code == '10000') {
      ElMessage.success("删除成功");
      getPage();
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    spinning.value = false;
  })
};

//删除取消
const deleteCancel = (e: MouseEvent) => {
};

//页面加载
onMounted(() => {
//初始化
  getInfo();
  getPage()
  getTree();
  getRoleList();
})

function getInfo(){
  request.get('/sysUser/info' ).then((res: any) => {
    queryFormInlineSubmit.value = null;
    if (res.code == '10000') {
      jzTableData.value.jzTable=res.data;
      let columnAll=jzTableData.value.jzTable.zjColumnList;
      jzTableData.value.jzTable.zjColumnList =columnAll.filter((tab) => tab.show == true)
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    console.log(error)
  })
}


function getRoleList() {
  spinning.value = true;
  request.get('/sysRole/list', {params: {StateEnum: 'NORMAL'}}).then((res: any) => {
    spinning.value = false;
    if (res.code == '10000') {
      roleList.value = res.data;
    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    spinning.value = false;
  })
}


/**
 * 刷新
 */
function refreshClick() {
  getPage()
}

function getPage() {
  spinning.value = true;
  request.get('/sysUser/page/' + jzTableData.value.jzPageData.current + '/' + jzTableData.value.jzPageData.size,  {params: queryFormInlineSubmit}).then((res: any) => {
    spinning.value = false;
    queryFormInlineSubmit.value = null;
    if (res.code == '10000') {
      jzTableData.value.jzPageData = res.data;

    } else {
      ElMessage.error(res.errorMessage);
    }
  }).catch((error) => {
    spinning.value = false;
  })
}




</script>